package xyz.second.ask_for_leave_manage_module.controller;

import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import xyz.second.ask_for_leave_manage_module.utils.DataMapper;
import xyz.second.ask_for_leave_manage_module.dto.AskForLeaveRequest;
import xyz.second.ask_for_leave_manage_module.serivce.AskForLeaveManageService;
import xyz.second.ask_for_leave_manage_module.vo.AskForLeaveInfo;
import xyz.second.common.auth.UserSessionData;

import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/ask_for_leave/student")
public class StudentAskForLeaveController {

    private final AskForLeaveManageService askForLeaveManageService;

    public StudentAskForLeaveController(AskForLeaveManageService askForLeaveManageService) {
        this.askForLeaveManageService = askForLeaveManageService;
    }

    @GetMapping("/ask/all")
    public List<AskForLeaveInfo> getAllAskForLeave(HttpSession session) {
        UserSessionData sessionData = (UserSessionData) session.getAttribute(UserSessionData.SESSION_DATA_KEY);
        return askForLeaveManageService.getStudentAskForLeaveRecord(sessionData.getAccount())
                .stream().map(DataMapper::askDataToInfo).collect(Collectors.toList());
    }

    @PostMapping("/ask/commit")
    public void askForLeave(@RequestBody @Validated AskForLeaveRequest askForLeaveRequest, HttpSession session) {
        UserSessionData sessionData = (UserSessionData) session.getAttribute(UserSessionData.SESSION_DATA_KEY);
        askForLeaveManageService.askForLeave(
            sessionData.getAccount(),
            askForLeaveRequest.getAskForReason()
        );
    }

}
